<template>
  <div class="party-building">
    <div class="page-header">
      <h1 class="page-title">党建工作</h1>
      <p class="page-subtitle">记录和管理党建活动参与情况</p>
    </div>

    <!-- 活动分类 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="组织生活" name="organization">
        <div class="actions-bar">
          <el-button type="primary" @click="openCreateActivity">
            <el-icon><Plus /></el-icon>
            记录组织生活
          </el-button>
        </div>

        <el-card>
          <el-table :data="organizationActivities" style="width: 100%" v-loading="loading.activities">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="type" label="活动类型" width="120" />
            <el-table-column prop="theme" label="活动主题" min-width="200" />
            <el-table-column prop="location" label="地点" width="150" />
            <el-table-column prop="host" label="主持人" width="120" />
            <el-table-column prop="participantCount" label="参与人数" width="100" />
            <el-table-column prop="absence" label="缺席" min-width="180" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="110">
              <template #default="{ row }">
                <el-tag :type="statusTagType(row.status)">{{ statusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="附件" width="120">
              <template #default="scope">
                <el-button type="primary" link @click="openAttachmentPreview(scope.row)">查看({{ scope.row.attachmentCount || 0 }})</el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="editActivity(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="confirmDeleteActivity(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="理论学习" name="study">
        <div class="actions-bar">
          <el-button type="primary" @click="openCreateStudy">
            <el-icon><Plus /></el-icon>
            记录学习活动
          </el-button>
        </div>

        <el-card>
          <el-table :data="studyActivities" style="width: 100%" v-loading="loading.studies">
            <el-table-column prop="date" label="学习日期" width="120" />
            <el-table-column prop="content" label="学习内容" min-width="220" />
            <el-table-column prop="form" label="学习形式" width="120" />
            <el-table-column prop="duration" label="学习时长" width="100" />
            <el-table-column prop="status" label="状态" width="110">
              <template #default="{ row }">
                <el-tag :type="statusTagType(row.status)">{{ statusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="small" @click="editStudy(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="confirmDeleteStudy(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="志愿服务" name="volunteer">
        <div class="actions-bar">
          <el-button type="primary" @click="openCreateVolunteer">
            <el-icon><Plus /></el-icon>
            记录志愿服务
          </el-button>
        </div>

        <el-card>
          <el-table :data="volunteerActivities" style="width: 100%" v-loading="loading.volunteers">
            <el-table-column prop="date" label="服务日期" width="120" />
            <el-table-column prop="name" label="活动名称" min-width="200" />
            <el-table-column prop="location" label="服务地点" width="150" />
            <el-table-column prop="duration" label="服务时长" width="100" />
            <el-table-column prop="status" label="状态" width="110">
              <template #default="{ row }">
                <el-tag :type="statusTagType(row.status)">{{ statusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="content" label="服务内容" min-width="200" />
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="small" @click="editVolunteer(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="confirmDeleteVolunteer(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加/编辑 组织生活 -->
    <el-dialog v-model="showAddDialog" :title="activityForm.id ? '编辑组织生活' : '记录组织生活'" width="680px">
      <el-form :model="activityForm" label-width="100px">
        <el-form-item label="活动类型">
          <el-select v-model="activityForm.type" style="width: 100%;">
            <el-option label="三会一课" value="三会一课" />
            <el-option label="主题党日" value="主题党日" />
            <el-option label="组织生活会" value="组织生活会" />
            <el-option label="民主评议党员" value="民主评议党员" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动主题">
          <el-input v-model="activityForm.theme" />
        </el-form-item>
        <el-form-item label="地点">
          <el-input v-model="activityForm.location" />
        </el-form-item>
        <el-form-item label="主持人">
          <el-input v-model="activityForm.host" />
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker v-model="activityForm.date" type="date" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="参与人数">
          <el-input-number v-model="activityForm.participantCount" :min="0" :max="9999" :step="1" />
        </el-form-item>
        <el-form-item label="缺席">
          <el-input v-model="activityForm.absence" type="textarea" :rows="2" placeholder="填写缺席人姓名及原因" />
        </el-form-item>
        <el-form-item label="活动记录">
          <el-input v-model="activityForm.record" type="textarea" :rows="6" placeholder="设置一个稍大的文本框" />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="#"
            :auto-upload="false"
            :file-list="uploadFileList"
            :on-change="handleAttachmentChange"
            :on-remove="handleAttachmentRemove"
            multiple
            accept="image/*,.pdf"
            list-type="text">
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">可添加附件（照片/pdf等），保存后自动上传到服务器</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" :loading="saving.activity" @click="submitActivity">保存</el-button>
      </template>
    </el-dialog>

    <!-- 附件预览对话框 -->
    <el-dialog v-model="showAttachmentDialog" title="附件预览" width="720px">
      <div v-if="currentAttachments.length === 0">暂无附件</div>
      <el-space wrap v-else>
        <div v-for="(f,idx) in currentAttachments" :key="idx" class="preview-item">
          <img v-if="f.previewType==='image'" :src="f.url" class="preview-img" />
          <el-link v-else :href="f.url" target="_blank" type="primary">打开PDF</el-link>
        </div>
      </el-space>
      <template #footer>
        <el-button type="primary" @click="showAttachmentDialog=false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑 理论学习 -->
    <el-dialog v-model="showStudyDialog" :title="studyForm.id ? '编辑学习记录' : '记录学习活动'" width="600px">
      <el-form :model="studyForm" label-width="100px">
        <el-form-item label="学习主题/内容">
          <el-input v-model="studyForm.topic" />
        </el-form-item>
        <el-form-item label="学习形式">
          <el-select v-model="studyForm.form" style="width: 100%">
            <el-option label="集中学习" value="集中学习" />
            <el-option label="自学" value="自学" />
            <el-option label="线上学习" value="线上学习" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="学习日期">
          <el-date-picker v-model="studyForm.date" type="date" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="学习时长">
          <el-input-number v-model="studyForm.hours" :min="0" :max="999" :step="0.5" />
        </el-form-item>
        <el-form-item label="心得体会">
          <el-input v-model="studyForm.notes" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showStudyDialog=false">取消</el-button>
        <el-button type="primary" :loading="saving.study" @click="submitStudy">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑 志愿服务 -->
    <el-dialog v-model="showVolunteerDialog" :title="volunteerForm.id ? '编辑志愿服务' : '记录志愿服务'" width="600px">
      <el-form :model="volunteerForm" label-width="100px">
        <el-form-item label="活动名称">
          <el-input v-model="volunteerForm.name" />
        </el-form-item>
        <el-form-item label="活动日期">
          <el-date-picker v-model="volunteerForm.date" type="date" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="服务地点">
          <el-input v-model="volunteerForm.location" />
        </el-form-item>
        <el-form-item label="服务时长">
          <el-input-number v-model="volunteerForm.hours" :min="0" :max="999" :step="0.5" />
        </el-form-item>
        <el-form-item label="活动内容">
          <el-input v-model="volunteerForm.content" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showVolunteerDialog=false">取消</el-button>
        <el-button type="primary" :loading="saving.volunteer" @click="submitVolunteer">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  createActivity, listActivities, updateActivity, deleteActivity,
  uploadActivityAttachment, listActivityAttachments
} from '@/api/party'
import { createStudy, getMyStudies, updateStudy, deleteStudy } from '@/api/theory'
import { createVolunteer, getMyVolunteers, updateVolunteer, deleteVolunteer } from '@/api/volunteer'

const activeTab = ref('organization')
const showAddDialog = ref(false)
const showStudyDialog = ref(false)
const showVolunteerDialog = ref(false)
const showAttachmentDialog = ref(false)
const userStore = useUserStore()

const loading = reactive({ activities: false, studies: false, volunteers: false })
const saving = reactive({ activity: false, study: false, volunteer: false })

const organizationActivities = ref([])
const studyActivities = ref([])
const volunteerActivities = ref([])

const activityForm = reactive({
  id: undefined,
  type: '',
  theme: '',
  location: '',
  host: '',
  date: '',
  participantCount: 0,
  absence: '',
  record: ''
})

const studyForm = reactive({ id: undefined, topic: '', form: '集中学习', date: '', hours: 0, notes: '' })
const volunteerForm = reactive({ id: undefined, name: '', date: '', hours: 0, location: '', content: '' })

const uploadFileList = ref([])
const currentAttachments = ref([])

const formatDate = (d) => {
  if (!d) return ''
  const date = typeof d === 'string' ? new Date(d) : d
  if (Number.isNaN(date.getTime())) return ''
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const dd = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${dd}`
}

const mapActivities = (list) => (list || []).map(a => ({
  id: a.id,
  type: a.activityType,
  theme: a.activitySubject,
  location: a.location,
  host: a.hostName,
  date: formatDate(a.activityDate || a.date),
  participantCount: a.participantCount,
  absence: a.absenceNotes,
  record: a.activityRecord,
  attachmentCount: a.attachmentCount || 0,
  status: a.status
}))

const mapStudies = (list) => (list || []).map(s => ({
  id: s.id,
  date: formatDate(s.studyDate || s.date),
  content: s.studyTopic,
  form: s.studyForm,
  duration: s.studyHours != null ? `${s.studyHours}小时` : '',
  _raw: s,
  status: s.status
}))

const mapVolunteers = (list) => (list || []).map(v => ({
  id: v.id,
  date: formatDate(v.serviceDate || v.date),
  name: v.serviceTitle,
  location: v.location,
  duration: v.serviceHours != null ? `${v.serviceHours}小时` : '',
  content: v.description,
  _raw: v,
  status: v.status
}))

const loadActivities = async () => {
  loading.activities = true
  try {
    const res = await listActivities({})
    const arr = res?.data || res || []
    organizationActivities.value = mapActivities(arr)
  } finally {
    loading.activities = false
  }
}

const loadStudies = async () => {
  loading.studies = true
  try {
    const res = await getMyStudies()
    const arr = res?.data || res || []
    studyActivities.value = mapStudies(arr)
  } finally {
    loading.studies = false
  }
}

const loadVolunteers = async () => {
  loading.volunteers = true
  try {
    const res = await getMyVolunteers()
    const arr = res?.data || res || []
    volunteerActivities.value = mapVolunteers(arr)
  } finally {
    loading.volunteers = false
  }
}

const openCreateActivity = () => {
  Object.assign(activityForm, { id: undefined, type:'', theme:'', location:'', host:'', date:'', participantCount:0, absence:'', record:'' })
  uploadFileList.value = []
  showAddDialog.value = true
}

const openAttachmentPreview = async (row) => {
  const res = await listActivityAttachments(row.id)
  const arr = res?.data || res || []
  currentAttachments.value = arr.map(f => ({
    name: f.fileName,
    url: f.fileUrl,
    previewType: String(f.fileName || '').toLowerCase().endsWith('.pdf') ? 'pdf' : 'image'
  }))
  showAttachmentDialog.value = true
}

const handleAttachmentChange = (file, fileList) => { uploadFileList.value = fileList }
const handleAttachmentRemove = (file, fileList) => { uploadFileList.value = fileList }

const submitActivity = async () => {
  if (!activityForm.type || !activityForm.theme || !activityForm.date) {
    ElMessage.warning('请至少填写活动类型、主题与日期')
    return
  }
  saving.activity = true
  try {
    const payload = {
      activity_type: activityForm.type,
      activity_subject: activityForm.theme,
      location: activityForm.location,
      host_name: activityForm.host,
      activity_date: formatDate(activityForm.date),
      participant_count: activityForm.participantCount,
      absence_notes: activityForm.absence,
      activity_record: activityForm.record
    }

    let activityId = activityForm.id
    if (activityId) {
      await updateActivity(activityId, payload)
    } else {
      const res = await createActivity(payload)
      activityId = (res && (res.id || res.data?.id))
    }

    // 上传附件
    if (activityId && uploadFileList.value?.length) {
      for (const f of uploadFileList.value) {
        await uploadActivityAttachment(activityId, f.raw || f)
      }
    }

    ElMessage.success('已保存')
    showAddDialog.value = false
    await loadActivities()
  } catch (e) {
    ElMessage.error(e?.response?.data?.message || e?.message || '保存失败')
  } finally {
    saving.activity = false
  }
}

const editActivity = (row) => {
  Object.assign(activityForm, {
    id: row.id,
    type: row.type,
    theme: row.theme,
    location: row.location,
    host: row.host,
    date: row.date,
    participantCount: row.participantCount,
    absence: row.absence,
    record: row.record
  })
  uploadFileList.value = []
  showAddDialog.value = true
}

const confirmDeleteActivity = async (row) => {
  await ElMessageBox.confirm('确定删除该记录？','提示',{type:'warning'})
  await deleteActivity(row.id)
  ElMessage.success('已删除')
  await loadActivities()
}

// 学习
const openCreateStudy = () => { Object.assign(studyForm, { id: undefined, topic:'', form:'集中学习', date:'', hours:0, notes:'' }); showStudyDialog.value = true }
const submitStudy = async () => {
  if (!studyForm.topic || !studyForm.date) { ElMessage.warning('请填写学习主题与日期'); return }
  saving.study = true
  try {
    const payload = {
      study_topic: studyForm.topic,
      study_form: studyForm.form,
      study_date: formatDate(studyForm.date),
      study_hours: studyForm.hours,
      notes: studyForm.notes
    }
    if (studyForm.id) await updateStudy(studyForm.id, payload)
    else await createStudy(payload)
    ElMessage.success('已保存')
    showStudyDialog.value = false
    await loadStudies()
  } catch (e) {
    ElMessage.error(e?.response?.data?.message || e?.message || '保存失败')
  } finally { saving.study = false }
}
const editStudy = (row) => {
  Object.assign(studyForm, { id: row.id, topic: row.content, form: row.form, date: row.date, hours: Number((row.duration||'').replace('小时','')) || 0, notes: row._raw?.notes || '' })
  showStudyDialog.value = true
}
const confirmDeleteStudy = async (row) => {
  await ElMessageBox.confirm('确定删除该记录？','提示',{type:'warning'})
  await deleteStudy(row.id)
  ElMessage.success('已删除')
  await loadStudies()
}

// 志愿服务
const openCreateVolunteer = () => { Object.assign(volunteerForm, { id: undefined, name:'', date:'', hours:0, location:'', content:'' }); showVolunteerDialog.value = true }
const submitVolunteer = async () => {
  if (!volunteerForm.name || !volunteerForm.date) { ElMessage.warning('请填写活动名称与日期'); return }
  saving.volunteer = true
  try {
    const payload = {
      service_title: volunteerForm.name,
      service_type: '志愿服务',
      service_date: formatDate(volunteerForm.date),
      service_hours: volunteerForm.hours,
      location: volunteerForm.location,
      description: volunteerForm.content
    }
    if (volunteerForm.id) await updateVolunteer(volunteerForm.id, payload)
    else await createVolunteer(payload)
    ElMessage.success('已保存')
    showVolunteerDialog.value = false
    await loadVolunteers()
  } catch (e) {
    ElMessage.error(e?.response?.data?.message || e?.message || '保存失败')
  } finally { saving.volunteer = false }
}
const editVolunteer = (row) => {
  Object.assign(volunteerForm, { id: row.id, name: row.name, date: row.date, hours: Number((row.duration||'').replace('小时','')) || 0, location: row.location, content: row.content })
  showVolunteerDialog.value = true
}
const confirmDeleteVolunteer = async (row) => {
  await ElMessageBox.confirm('确定删除该记录？','提示',{type:'warning'})
  await deleteVolunteer(row.id)
  ElMessage.success('已删除')
  await loadVolunteers()
}

const handleTabClick = (tab) => { /* 需要时可按需加载 */ }

onMounted(async () => {
  await Promise.all([loadActivities(), loadStudies(), loadVolunteers()])
})

// 状态中文与颜色
const statusText = (s) => ({ PENDING: '待审核', APPROVED: '已通过', REJECTED: '已驳回' }[s] || s)
const statusTagType = (s) => ({ PENDING: 'warning', APPROVED: 'success', REJECTED: 'danger' }[s] || 'info')
</script>

<style scoped>
.party-building {
  max-width: 1200px;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.actions-bar {
  margin-bottom: 20px;
}

.preview-item { width: 200px; height: 140px; display: flex; align-items: center; justify-content: center; border: 1px dashed #dcdfe6; border-radius: 6px; overflow: hidden; }
.preview-img { max-width: 100%; max-height: 100%; display: block; }
</style>